package com.zhazhapan.efo.util;

import com.alibaba.fastjson.JSONObject;
import com.zhazhapan.efo.modules.constant.DefaultValues;
import com.zhazhapan.util.Checker;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.security.SecureRandom;

/**
 * @author admin
 * @since 2019/12/30
 */
public class ControllerUtils {

    private ControllerUtils() {}

    /**
     * 获取一个简单的响应状态
     *
     * @param isSuccess 是否操作成功
     *
     * @return 响应JSON字符串
     */
    public static String getResponse(boolean isSuccess) {
        JSONObject jsonObject = new JSONObject();
        if (isSuccess) {
            jsonObject.put("status", "success");
        } else {
            jsonObject.put("status", "error");
        }
        return jsonObject.toString();
    }

    private static byte[] decryptFile(byte[] encryptedData, String password) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        SecureRandom secureRandom = new SecureRandom(password.getBytes());
        keyGenerator.init(128, secureRandom);
        SecretKey secretKey = keyGenerator.generateKey();
        byte[] keyBytes = secretKey.getEncoded();
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
        return cipher.doFinal(encryptedData);
    }

    /**
     * 加载本地资源
     *
     * @param response 返回的Response
     * @param path 资源路径
     * @param download 直接下载
     */
    public static void loadResource(HttpServletResponse response, String path, String psd, boolean download) throws IOException {
        if (Checker.isNotEmpty(path)) {
            File file = new File(path);
            if (download) {
                setResponseFileName(response, file.getName());
            }

            byte[] fileData = Files.readAllBytes(file.toPath());

            if (psd != null) {
                try {
                    // 使用密码解密文件
                    fileData = decryptFile(fileData, psd);
                } catch (Exception e) {
                    response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                    response.getWriter().write("文件解密失败");
                    return;
                }
            }

            ServletOutputStream os = response.getOutputStream();
            os.write(fileData);
            os.flush();
            os.close();
        } else {
            response.sendRedirect(DefaultValues.NOT_FOUND_PAGE);
        }
    }

    /**
     * 设置响应头的文件名
     *
     * @param response {@link HttpServletResponse}
     * @param fileName 文件名
     */
    public static void setResponseFileName(HttpServletResponse response, String fileName) throws
            UnsupportedEncodingException {
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),
                "ISO-8859-1"));
    }
}
